package com.github.binarylei.kafka;

import kafka.consumer.Consumer;
import kafka.consumer.ConsumerConfig;
import kafka.consumer.ConsumerIterator;
import kafka.consumer.KafkaStream;
import kafka.javaapi.consumer.ConsumerConnector;
import kafka.javaapi.producer.Producer;
import kafka.producer.KeyedMessage;
import kafka.producer.ProducerConfig;
import kafka.serializer.StringDecoder;
import kafka.utils.VerifiableProperties;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.TimeUnit;

/**
 * @author: leigang
 * @version: 2018-04-12
 */
public class KafkaConsumer {

    public static void main(String[] args) {
        Properties properties = new Properties();

        Properties props = new Properties();
        props.put("zookeeper.connect", "127.0.0.1:2181");
        props.put("zookeeper.session.timeout.ms", "4000");
        props.put("zookeeper.sync.timeout.ms", "1000");
        props.put("auto.commit.interval.ms", "1000");
        props.put("atuo.offset.reset", "smallest");
        // group 代表一个消费组
        props.put("group.id", "group1");
        props.put("serializer.class", "kafka.serializer.StringEncoder");

        ConsumerConfig config = new ConsumerConfig(props);
        ConsumerConnector consumer = Consumer.createJavaConsumerConnector(config);

        HashMap<String, Integer> topicCountMap = new HashMap<>();
        topicCountMap.put("test", new Integer(1));

        StringDecoder keyDecoder = new StringDecoder(new VerifiableProperties());
        StringDecoder valueDecoder = new StringDecoder(new VerifiableProperties());

        Map<String, List<KafkaStream<String, String>>> consumerMap = consumer.createMessageStreams(topicCountMap, keyDecoder, valueDecoder);
        KafkaStream<String, String> stream = consumerMap.get("test").get(0);
        ConsumerIterator<String, String> it = stream.iterator();
        while (it.hasNext()) {
            System.out.println(it.next().message());
        }
    }
}
